<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>js防抖与节流</title>
</head>
<body>
    <h2>js防抖与节流</h2>
    <p class="jsShowText"></p>
    <input placeholder="请输入电话">
    
    <div id="ele2" class="con" style="background-color: aquamarine; min-height: 200px;"></div>
</body>
<script>
    // 防抖debounce --> 固定的时间内，时间只允许发生一次（将多次操作变成一次）
    let ele = document.querySelector('input');
    // ele.addEventListener('input', demo) // 现象
    ele.addEventListener('input', debounce(demo, 1000)) // js防抖

    function debounce (fn, time) {
        let timer = null;
        return args => {
            if (timer) clearTimeout(timer)
            timer = setTimeout(fn, time)
        }
    }
    let num = 0;
    const jsShowText = document.querySelector('.jsShowText')
    function demo() {
        jsShowText.innerHTML = num++;
    }

    // 节流throttle --> 一定时间内多个事情合为一个（场景：1.提交表单；2.高频监听事件）
    let ele2 = document.querySelector('#ele2');
    // ele2.addEventListener('touchmove', demo) // 现象
    ele2.addEventListener('touchmove', throttle(demo, 1000))    // js节流

    // 节流-定时器版本
    function throttle (fn, time) {
        let timer = null;
        return args => {
            if(!timer) {
                timer = setTimeout(() => {
                    fn();
                    timer = null;
                }, time)
            }
        }
    }
    // 节流-时间戳版本
    // function throttle (fn, time) {
    //     let pre = 0;
    //     return args => {
    //         let now = Date.now()
    //         if (now - pre > time) {
    //             fn();
    //             pre = now;
    //         }
    //     }
    // }
    // https://juejin.cn/post/6844903651278848014#heading-1
</script>
</html>